/**
 * Created by zxr on 16/11/17.
 */
var socketio = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var nameUserd = [];
var currentRoom = {};
var Room = '俱乐部';

exports.listen  = function(server){
	io = socketio.listen(server);
	io.set('log level', 1);
	io.sockets.on('connect', function(socket){
		guestNumber = assignGuestName(socket, guestNumber, nickNames, nameUserd);
		joinRoom(socket,Room);
		handleMessageBroadcasting(socket,nickNames);
		changeName(socket, nickNames, nameUserd);
		handleRoomJoining(socket);
		socket.on('rooms', function(){
			socket.emit('rooms', io.sockets.adapter.rooms)
		});
		handleClientLeave(socket,nickNames,nameUserd);
	})
};

//分配用户昵称
function assignGuestName(socket, guestNumber, nickNames, nameUserd){
	var name = 'Guest' + guestNumber;
	nickNames[socket.id] = name;
	socket.emit('nameResult',{
		success: true,
		name: name
	});
	nameUserd.push(name);
	return guestNumber + 1;
}
function joinRoom(socket, room){
	// 记录用户的当前房间号
	socket.join(room); //让用户进入房间
	currentRoom[socket.id] = room;
	socket.emit('joinResult', {room:room,message:'welcome ' + room + ' join!'});
	// 让房间里的其他用户知道 有新用户进入
	console.log(nickNames[socket.id] + '---' + room);
	socket.broadcast.to(room).emit('message',{
		text:nickNames[socket.id] + ' has join ' + room + ':'
	});
	//确定有哪些用户在房间
	var usersInRoom = io.sockets.adapter.rooms[room];
	if (usersInRoom.length > 1){
		var usersInRoomSummary = 'Users currently in' + room + ':';
		var tt = Object.keys(usersInRoom.sockets);
		for (var i = 0; i < tt.length; i++){
			var userSocketId = tt[i];
			if (userSocketId != socket.id){
				usersInRoomSummary += ', ';
			}
			usersInRoomSummary += nickNames[userSocketId]
		}
		usersInRoomSummary += '. ';
		// 将房间里的其他用户汇总发给其他用户
		socket.emit('message',{text:usersInRoomSummary});
	}

}


// 用户发起更名请求
function changeName(socket, nickNames, nameUsed){
	socket.on('nameAttempt',function(name){
		// 不能以Guest开头
		if (name.indexOf('Guest') == 0){
			socket.emit('nameResult',{
				text: 'Name cannot begin with "Guest" .'
			});
		} else {
			if (nameUsed.indexOf(name) == -1){
				var previousName = nickNames[socket.id];
				var previousNameIndex = nameUsed.indexOf(previousName);
				nameUsed.push(name);
				nickNames[socket.id]  = name;
				delete nameUsed[previousNameIndex];
				socket.emit('nameResult', {
					success: true,
					name: name,
					text:'You has change name as ' + name
				});
				socket.broadcast.to(currentRoom[socket.id]).emit('message', {
					text: previousName + ' is has change name as ' + name + '.'
				});
			} else {
				socket.emit('nameResult', {
					success: false,
					message: ' this name has already in use!'
				})
			}

		}
	});
};
// 转发用户发出的消息
 function handleMessageBroadcasting(socket,nickNames){
	 socket.on('send-message',function(message){
		 console.log(message)
		 socket.broadcast.to(message.room).emit('broadcast-message',{
			 text:nickNames[socket.id] + ':' + message.text
		 });
	 });
 };

// 更换房间
function handleRoomJoining(socket){
	socket.on('join', function(room){
		socket.leave(currentRoom[socket.id]);
		joinRoom(socket,room.newRoom);
	})
};
// 用户离开房间
function handleClientLeave(socket,nickNames,nameUserd){
	socket.on('disconnect',function(){
		var nameIndex = nameUserd.indexOf(nickNames[socket.id]);
		var leaveUser = nameUserd[nameIndex];
		delete  nameUserd[nameIndex];
		delete  nickNames[socket.id];
		socket.broadcast.to(Room).emit('leave',{
			text: leaveUser + ' has leave the ' + Room + ';'
		})
	})
}

//function time(socket){
//	var timer = new Date().toUTCString();
//	socket.emit('time',timer);
//}
//setInterval(time,1000);